using JT808Protocol.Common;
using JT808Protocol.Models.JsonConverters;
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace JT808Protocol.Models
{
    [JsonConverter(typeof(MsgHeaderHumanizeConverter))]
    public class JT808Header : IJT808Header
    {
        /// <summary>
        /// 消息ID
        /// </summary>
        [JsonPropertyName("消息ID值")] public ushort MessageID { get; set; }

        /// <summary>
        /// 消息类型
        /// </summary>
        [JsonPropertyName("消息类型")] public EnumMessageType MessageType { get { return (EnumMessageType)MessageID; } }

        /// <summary>
        /// 消息体属性
        /// </summary>
        [JsonPropertyName("消息体属性")] public JT808MessageBodyProperties MessageBodyProperties { get; set; }

        /// <summary>
        /// 协议版本号
        /// </summary>
        [JsonPropertyName("协议版本号")]
        public JT808ProtocolVersion ProtocolVersion
        {
            get
            {
                return _protocolVer;
            }
            set
            {
                _protocolVer = value;
                MessageBodyProperties.IsSupport2019OrUpper = (_protocolVer == JT808ProtocolVersion.v2019) ? true : false;
            }
        }

        /// <summary>
        /// 终端手机号 BCD[n]
        /// 2019、粤标 n为10；2013、苏标 n为6
        /// </summary>
        [JsonPropertyName("终端手机号")] public string SimNumber { get; set; }

        /// <summary>
        /// 消息流水号
        /// </summary>
        [JsonPropertyName("消息流水号")] public ushort SerialNumber { get; set; }

        /// <summary>
        /// 消息封装项
        /// </summary>
        [JsonPropertyName("消息封装项")] public PackageInfo PackageInfo { get; set; }

        #region 私有属性

        private JT808ProtocolVersion _protocolVer;

        #endregion 私有属性

        /// <summary>
        /// 无参构造
        /// </summary>
        public JT808Header()
        {
            MessageBodyProperties = new JT808MessageBodyProperties();
            MessageBodyProperties.IsSplitPackage = false;//不分包
        }

        /// <summary>
        /// 构造消息头
        /// </summary>
        /// <param name="msgType">消息类型枚举 </param>
        /// <param name="simNumber">Sim卡号（手机号）</param>
        /// <param name="serialNumber">消息流水号</param>
        /// <param name="msgBodyLen">消息体长度</param>
        /// <param name="protocolVersion">版本类型</param>
        public JT808Header(EnumMessageType msgType = EnumMessageType.平台通用应答, string simNumber = "", ushort serialNumber = 0, ushort msgBodyLen = 0, JT808ProtocolVersion protocolVersion = JT808ProtocolVersion.v2019)
        {
            MessageBodyProperties = new JT808MessageBodyProperties();

            this.MessageID = (ushort)msgType;
            this.SerialNumber = serialNumber;
            this.SimNumber = simNumber;
            this.ProtocolVersion = protocolVersion;

            MessageBodyProperties.IsSupport2019OrUpper = (protocolVersion == JT808ProtocolVersion.v2019) ? true : false;
            MessageBodyProperties.IsSplitPackage = false;//不分包
            MessageBodyProperties.BodyLength = msgBodyLen;
        }

        /// <summary>
        /// 构造消息头
        /// </summary>
        /// <param name="msgId">消息ID</param>
        /// <param name="simNumber">Sim卡号（手机号）</param>
        /// <param name="serialNumber">消息流水号</param>
        /// <param name="msgBodyLen">消息体长度</param>
        /// <param name="protocolVersion">版本类型</param>
        public JT808Header(ushort msgId, string simNumber, ushort serialNumber, ushort msgBodyLen = 0, JT808ProtocolVersion protocolVersion = JT808ProtocolVersion.v2019)
        {
            MessageBodyProperties = new JT808MessageBodyProperties();

            this.MessageID = msgId;
            this.SerialNumber = serialNumber;
            this.SimNumber = simNumber;
            this.ProtocolVersion = protocolVersion;

            MessageBodyProperties.IsSupport2019OrUpper = (protocolVersion == JT808ProtocolVersion.v2019) ? true : false;
            MessageBodyProperties.IsSplitPackage = false;//不分包
            MessageBodyProperties.BodyLength = msgBodyLen;
        }

        public IJT808Header ReadHeader(ReadOnlySpan<byte> data, ref int index)
        {
            MessageID = ParseHelper.Uint16(ref data, index);
            index += 2;
            MessageBodyProperties = new JT808MessageBodyProperties();

            byte _2 = (byte)(data[index] & 0x03);
            byte[] buffLen = new byte[] { _2, data[index + 1] };

            MessageBodyProperties.BodyLength = ParseHelper.Uint16(ref buffLen, 0);

            MessageBodyProperties.EncrytionType = ((byte)(data[index] & 0x04) == 0x04) ?
                EnumEncrytionType.RSA : EnumEncrytionType.不加密;
            MessageBodyProperties.IsSplitPackage = ((byte)(data[index] & 0x20) == 0x20);
            MessageBodyProperties.IsSupport2019OrUpper = ((byte)(data[index] & 0x40) == 0x40);

            index += 2;

            int phoneNumberLen = 10;//默认为2013以上版本，终端手机号长度为10
            if (MessageBodyProperties.IsSupport2019OrUpper)
            {
                this.ProtocolVersion = (JT808ProtocolVersion)data[index];
                index++;
            }
            else
            {
                this.ProtocolVersion = JT808ProtocolVersion.v2013;
                phoneNumberLen = 6;//2013及以下版本，终端手机号长度为6
            }

            for (int i = 0; i < phoneNumberLen; i++)
            {
                SimNumber += ParseHelper.BcdToString(data[index + i]);
            }

            SimNumber = SimNumber.Substring(SimNumber.Length - 11);
            index += phoneNumberLen;
            SerialNumber = ParseHelper.Uint16(ref data, index);
            index += 2;

            if (MessageBodyProperties.IsSplitPackage)
            {
                this.PackageInfo = new PackageInfo();
                this.PackageInfo.PackageIndex = data[index + 2];
                this.PackageInfo.PackageTotal = data[index + 4];
            }

            return this;
        }

        public List<byte> WriteToBytes()
        {
            List<byte> headerBytes = new List<byte>();

            //消息ID
            headerBytes.AddRange(ParseHelper.Bytes(MessageID));

            #region 消息体属性

            var msgBodyProperty = ushort.MinValue;
            // 第14/15位 固定为1
            msgBodyProperty |= 1 << 14;
            //是否分包
            if (MessageBodyProperties.IsSplitPackage)
            {
                msgBodyProperty |= 1 << 13;
            }
            //加密方式
            if (MessageBodyProperties.EncrytionType == EnumEncrytionType.RSA)
            {
                msgBodyProperty |= 1 << 10;
            }
            //消息体长度
            msgBodyProperty |= (ushort)MessageBodyProperties.BodyLength;
            headerBytes.AddRange(ParseHelper.Bytes(msgBodyProperty));

            #endregion 消息体属性

            //终端手机号
            headerBytes.AddRange(ParseHelper.StringToBCD(SimNumber, (ushort)SimNumber.Length));

            //消息流水号
            headerBytes.AddRange(ParseHelper.Bytes(SerialNumber));

            return headerBytes;
        }
    }

    /// <summary>
    /// 消息封装项
    /// </summary>
    public class PackageInfo
    {
        /// <summary>
        /// 消息包总数
        /// </summary>
        [JsonPropertyName("消息包总数")]
        public ushort PackageTotal { get; set; }

        /// <summary>
        /// 消息包序号
        /// </summary>
        [JsonPropertyName("消息包序号")]
        public ushort PackageIndex { get; set; }
    }
}